package com.ems.pay.service;

import java.math.BigDecimal;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ems.common.base.BaseException;
import com.ems.pay.domain.AccountEntity;
import com.ems.pay.exception.PayBusinessException;
@Service("payService")
@Transactional(readOnly=true) // 下面所有方法使用默认事务配置
public class PayServiceImpl implements PayService {
	
	@Autowired
	private SessionFactory sessionFactory;

	@Transactional(propagation=Propagation.REQUIRED, 
			isolation=Isolation.READ_COMMITTED, rollbackFor= {BaseException.class, Exception.class})
	public void transferAccounts() {
		Session session = sessionFactory.getCurrentSession();
		// 查询A账号信息
		AccountEntity a = session.get(AccountEntity.class, 1L);
		// 查询B账号信息
		AccountEntity b = session.get(AccountEntity.class, 2L);
		// 执行转账
		b.setAccountMoney(b.getAccountMoney().subtract(new BigDecimal(200)));
		a.setAccountMoney(a.getAccountMoney().add(new BigDecimal(200)));
		try {
			// 开启事务
			// 更新账号
			session.update(b);
			session.update(a);
			// 提交事务
		} catch (Exception e) {
			// 回滚
			throw new PayBusinessException("转账失败.....");
		}
	}
}
